// 字段类型配置
const fieldTypes = {
    'string': { label: '📝 文本输入框', goType: 'string', defaultSize: 255, frontendType: 'input' },
    'text': { label: '📄 文本域', goType: 'string', defaultSize: 1000, frontendType: 'textarea' },
    'richtext': { label: '📝 富文本编辑器', goType: 'string', defaultSize: 5000, frontendType: 'richtext' },
    'int': { label: '🔢 数字输入', goType: 'int', defaultSize: null, frontendType: 'number' },
    'uint': { label: '🔢 正整数', goType: 'uint', defaultSize: null, frontendType: 'number' },
    'float64': { label: '🔢 小数', goType: 'float64', defaultSize: null, frontendType: 'number' },
    'decimal': { label: '💰 金额', goType: 'decimal', defaultSize: null, frontendType: 'number' },
    'bool': { label: '☑️ 开关', goType: 'bool', defaultSize: null, frontendType: 'switch' },
    'time': { label: '⏰ 时间选择', goType: 'time.Time', defaultSize: null, frontendType: 'time' },
    'date': { label: '📅 日期选择', goType: 'time.Time', defaultSize: null, frontendType: 'date' },
    'datetime': { label: '📅 日期时间', goType: 'time.Time', defaultSize: null, frontendType: 'datetime' },
    'image': { label: '🖼️ 图片上传', goType: 'string', defaultSize: 500, frontendType: 'image' },
    'file': { label: '📎 文件上传', goType: 'string', defaultSize: 500, frontendType: 'file' },
    'select': { label: '📋 下拉选择', goType: 'int', defaultSize: null, frontendType: 'select' },
    'radio': { label: '⚪ 单选按钮', goType: 'int', defaultSize: null, frontendType: 'radio' },
    'checkbox': { label: '☑️ 多选框', goType: 'string', defaultSize: 500, frontendType: 'checkbox' },
    'email': { label: '📧 邮箱', goType: 'string', defaultSize: 255, frontendType: 'email' },
    'phone': { label: '📱 手机号', goType: 'string', defaultSize: 20, frontendType: 'phone' },
    'url': { label: '🔗 网址', goType: 'string', defaultSize: 500, frontendType: 'url' },
    'password': { label: '🔒 密码', goType: 'string', defaultSize: 255, frontendType: 'password' },
    'color': { label: '🎨 颜色选择', goType: 'string', defaultSize: 10, frontendType: 'color' }
};

let fieldCounter = 0;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 添加默认字段
    addDefaultFields();
    
    // 监听模型名称变化，自动生成表名
    document.getElementById('modelName').addEventListener('input', function() {
        const modelName = this.value;
        const tableName = modelName.toLowerCase().replace(/([A-Z])/g, '_$1').replace(/^_/, '');
        document.getElementById('tableName').value = tableName;
    });
});

// 添加默认字段
function addDefaultFields() {
    // ID字段
    addField({
        name: 'id',
        type: 'uint',
        comment: 'ID',
        primary: true,
        required: false,
        size: null
    });
    
    // 创建时间
    addField({
        name: 'created_at',
        type: 'time',
        comment: '创建时间',
        primary: false,
        required: false,
        size: null
    });
    
    // 更新时间
    addField({
        name: 'updated_at',
        type: 'time',
        comment: '更新时间',
        primary: false,
        required: false,
        size: null
    });
    
    // 删除时间
    addField({
        name: 'deleted_at',
        type: 'time',
        comment: '删除时间',
        primary: false,
        required: false,
        size: null
    });
}

// 预设字段模板
const fieldPresets = {
    'name': {
        name: 'name',
        type: 'string',
        comment: '名称',
        size: 100,
        required: true
    },
    'status': {
        name: 'status',
        type: 'select',
        comment: '状态',
        default: 1,
        options: '1:启用,0:禁用'
    },
    'sort': {
        name: 'sort',
        type: 'int',
        comment: '排序',
        default: 0
    },
    'description': {
        name: 'description',
        type: 'text',
        comment: '描述',
        size: 500
    }
};

// 添加预设字段
function addPresetField(presetType) {
    const preset = fieldPresets[presetType];
    if (preset) {
        addField(preset);
    }
}

// 将Go类型映射到前端字段类型
function mapGoTypeToFieldType(goType) {
    const typeMapping = {
        'int': 'int',
        'uint': 'uint',
        'string': 'string',
        'float64': 'float64',
        'decimal': 'decimal',
        'bool': 'bool',
        'time.Time': 'datetime'
    };

    return typeMapping[goType] || 'string';
}

// 添加字段
function addField(fieldData = null) {
    fieldCounter++;
    const container = document.getElementById('fieldsContainer');
    
    const fieldDiv = document.createElement('div');
    fieldDiv.className = 'field-item';
    fieldDiv.id = `field-${fieldCounter}`;
    
    const isDefault = fieldData && ['id', 'created_at', 'updated_at', 'deleted_at'].includes(fieldData.name);
    
    fieldDiv.innerHTML = `
        <div class="field-header">
            <span class="field-title">字段 ${fieldCounter}</span>
            ${!isDefault ? `<button type="button" class="remove-field" onclick="removeField(${fieldCounter})">删除</button>` : ''}
        </div>
        
        <div class="field-grid">
            <div class="form-group">
                <label>字段名称 *</label>
                <input type="text" name="fieldName" placeholder="例如: name" value="${fieldData?.name || ''}" ${isDefault ? 'readonly' : ''} required>
            </div>
            <div class="form-group">
                <label>字段类型 *</label>
                <select name="fieldType" onchange="updateFieldOptions(this)" ${isDefault ? 'disabled' : ''} required>
                    ${Object.entries(fieldTypes).map(([key, type]) => 
                        `<option value="${key}" ${fieldData?.type === key ? 'selected' : ''}>${type.label}</option>`
                    ).join('')}
                </select>
            </div>
            <div class="form-group">
                <label>字段描述</label>
                <input type="text" name="fieldComment" placeholder="例如: 商品名称" value="${fieldData?.comment || ''}">
            </div>
        </div>
        
        <div class="field-grid">
            <div class="form-group">
                <label>字段长度</label>
                <input type="number" name="fieldSize" placeholder="例如: 255" value="${fieldData?.size || ''}">
            </div>
            <div class="form-group">
                <label>默认值</label>
                <input type="text" name="fieldDefault" placeholder="例如: 0" value="${fieldData?.default || ''}">
            </div>
            <div class="form-group">
                <label>验证规则</label>
                <input type="text" name="fieldValidation" placeholder="例如: required,min:3,max:50" value="">
            </div>
        </div>

        <div class="field-grid">
            <div class="form-group">
                <label>选项值 (选择框/单选框)</label>
                <textarea name="fieldOptions" placeholder="格式: 1:启用,0:禁用" rows="2"></textarea>
            </div>
            <div class="form-group">
                <label>前端组件类型</label>
                <select name="frontendType">
                    <option value="auto">自动选择</option>
                    <option value="input">文本输入框</option>
                    <option value="textarea">文本域</option>
                    <option value="number">数字输入</option>
                    <option value="select">下拉选择</option>
                    <option value="radio">单选按钮</option>
                    <option value="checkbox">复选框</option>
                    <option value="switch">开关</option>
                    <option value="date">日期选择</option>
                    <option value="time">时间选择</option>
                    <option value="datetime">日期时间</option>
                    <option value="image">图片上传</option>
                    <option value="file">文件上传</option>
                    <option value="richtext">富文本编辑器</option>
                </select>
            </div>
            <div class="form-group">
                <label>列表显示</label>
                <select name="listDisplay">
                    <option value="show">显示</option>
                    <option value="hide">隐藏</option>
                    <option value="searchable">可搜索</option>
                </select>
            </div>
        </div>
        
        <div class="field-options">
            <div class="checkbox-group">
                <input type="checkbox" name="fieldPrimary" ${fieldData?.primary ? 'checked' : ''} ${isDefault && fieldData?.name !== 'id' ? 'disabled' : ''}>
                <label>主键</label>
            </div>
            <div class="checkbox-group">
                <input type="checkbox" name="fieldRequired" ${fieldData?.required ? 'checked' : ''}>
                <label>必填</label>
            </div>
            <div class="checkbox-group">
                <input type="checkbox" name="fieldUnique">
                <label>唯一</label>
            </div>
            <div class="checkbox-group">
                <input type="checkbox" name="fieldIndex">
                <label>索引</label>
            </div>
        </div>
    `;
    
    container.appendChild(fieldDiv);
    
    // 更新字段选项
    const typeSelect = fieldDiv.querySelector('select[name="fieldType"]');
    updateFieldOptions(typeSelect);
}

// 删除字段
function removeField(fieldId) {
    const fieldElement = document.getElementById(`field-${fieldId}`);
    if (fieldElement) {
        fieldElement.remove();
    }
}

// 更新字段选项
function updateFieldOptions(selectElement) {
    const fieldDiv = selectElement.closest('.field-item');
    const sizeInput = fieldDiv.querySelector('input[name="fieldSize"]');
    const selectedType = selectElement.value;
    const typeConfig = fieldTypes[selectedType];
    
    if (typeConfig.defaultSize) {
        sizeInput.value = typeConfig.defaultSize;
        sizeInput.placeholder = `建议: ${typeConfig.defaultSize}`;
    } else {
        sizeInput.value = '';
        sizeInput.placeholder = '不需要设置长度';
    }
}

// 收集表单数据
function collectFormData() {
    const formData = {
        model: {
            name: document.getElementById('modelName').value,
            table: document.getElementById('tableName').value,
            comment: document.getElementById('comment').value,
            fields: []
        }
    };
    
    const fieldItems = document.querySelectorAll('.field-item');
    fieldItems.forEach(fieldItem => {
        const fieldData = {
            name: fieldItem.querySelector('input[name="fieldName"]').value,
            type: fieldItem.querySelector('select[name="fieldType"]').value,
            comment: fieldItem.querySelector('input[name="fieldComment"]').value,
            size: parseInt(fieldItem.querySelector('input[name="fieldSize"]').value) || null,
            default: fieldItem.querySelector('input[name="fieldDefault"]').value || null,
            primary: fieldItem.querySelector('input[name="fieldPrimary"]').checked,
            required: fieldItem.querySelector('input[name="fieldRequired"]').checked,
            unique: fieldItem.querySelector('input[name="fieldUnique"]').checked,
            index: fieldItem.querySelector('input[name="fieldIndex"]').checked
        };
        
        // 转换为Go类型
        const typeConfig = fieldTypes[fieldData.type];
        fieldData.type = typeConfig.goType;
        
        formData.model.fields.push(fieldData);
    });
    
    return formData;
}

// 预览配置
function previewConfig() {
    const data = collectFormData();
    const yamlContent = generateYAML(data);
    
    document.getElementById('previewContent').textContent = yamlContent;
    document.getElementById('previewSection').style.display = 'block';
    
    // 滚动到预览区域
    document.getElementById('previewSection').scrollIntoView({ behavior: 'smooth' });
}

// 生成YAML格式
function generateYAML(data) {
    let yaml = `# ${data.model.comment || data.model.name} 模型配置\n`;
    yaml += `model:\n`;
    yaml += `  name: "${data.model.name}"\n`;
    yaml += `  table: "${data.model.table}"\n`;
    yaml += `  comment: "${data.model.comment}"\n`;
    yaml += `  fields:\n`;
    
    data.model.fields.forEach(field => {
        yaml += `    - name: "${field.name}"\n`;
        yaml += `      type: "${field.type}"\n`;
        if (field.size) yaml += `      size: ${field.size}\n`;
        if (field.primary) yaml += `      primary: true\n`;
        if (field.required) yaml += `      required: true\n`;
        if (field.unique) yaml += `      unique: true\n`;
        if (field.default !== null && field.default !== '') yaml += `      default: ${field.default}\n`;
        yaml += `      comment: "${field.comment}"\n`;
        yaml += `\n`;
    });
    
    return yaml;
}

// 保存配置
async function saveConfig() {
    const data = collectFormData();
    
    if (!data.model.name || !data.model.table) {
        alert('请填写模型名称和表名');
        return;
    }
    
    try {
        const response = await fetch('/api/save-config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            alert('配置保存成功！');
        } else {
            alert('保存失败，请重试');
        }
    } catch (error) {
        console.error('保存配置失败:', error);
        alert('保存失败，请检查网络连接');
    }
}

// 生成代码
async function generateCode() {
    const data = collectFormData();

    if (!data.model.name || !data.model.table) {
        alert('请填写模型名称和表名');
        return;
    }

    try {
        const response = await fetch('/api/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        if (response.ok) {
            const result = await response.json();
            alert(`代码生成成功！\n生成了 ${result.fileCount} 个文件`);
        } else {
            alert('生成失败，请重试');
        }
    } catch (error) {
        console.error('生成代码失败:', error);
        alert('生成失败，请检查网络连接');
    }
}

// 从数据库导入表结构
async function importFromDatabase() {
    const tableName = document.getElementById('dbTable').value;

    if (!tableName) {
        alert('请输入数据库表名');
        return;
    }

    try {
        const response = await fetch('/api/import-table', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ table: tableName })
        });

        if (response.ok) {
            const result = await response.json();
            console.log('数据库导入结果:', result); // 调试信息

            // 清空现有字段
            document.getElementById('fieldsContainer').innerHTML = '';
            fieldCounter = 0;

            // 填充基本信息
            document.getElementById('modelName').value = result.Model.Name;
            document.getElementById('tableName').value = result.Model.Table;
            document.getElementById('comment').value = result.Model.Comment;

            // 添加字段
            result.Model.Fields.forEach(field => {
                // 转换字段数据格式
                const fieldData = {
                    name: field.Name,
                    type: mapGoTypeToFieldType(field.Type), // 映射Go类型到前端类型
                    comment: field.Comment,
                    size: field.Size,
                    primary: field.Primary,
                    required: field.Required,
                    default: field.Default
                };
                addField(fieldData);
            });

            alert('数据库表结构导入成功！');
        } else {
            const error = await response.text();
            alert(`导入失败: ${error}`);
        }
    } catch (error) {
        console.error('导入失败:', error);
        alert('导入失败，请检查网络连接');
    }
}

// 加载已有配置
async function loadExistingConfig() {
    try {
        const response = await fetch('/api/models');

        if (response.ok) {
            const models = await response.json();

            if (models.length === 0) {
                alert('没有找到已有的模型配置');
                return;
            }

            const modelName = prompt(`请选择要加载的模型配置:\n${models.map((m, i) => `${i + 1}. ${m}`).join('\n')}\n\n请输入模型名称:`);

            if (modelName && models.includes(modelName)) {
                const configResponse = await fetch(`/api/config/${modelName}`);
                if (configResponse.ok) {
                    const config = await configResponse.json();
                    loadConfigToForm(config);
                    alert('配置加载成功！');
                } else {
                    alert('加载配置失败');
                }
            }
        } else {
            alert('获取模型列表失败');
        }
    } catch (error) {
        console.error('加载配置失败:', error);
        alert('加载配置失败，请检查网络连接');
    }
}

// 将配置加载到表单
function loadConfigToForm(config) {
    // 清空现有字段
    document.getElementById('fieldsContainer').innerHTML = '';
    fieldCounter = 0;

    // 填充基本信息
    document.getElementById('modelName').value = config.model.name;
    document.getElementById('tableName').value = config.model.table;
    document.getElementById('comment').value = config.model.comment;

    // 添加字段
    config.model.fields.forEach(field => {
        addField(field);
    });
}
